<template>
  <div class="insp">
    <div class="insp-header">
      <div class="flexBetween">
        <div class="flex insp-header-left">
          <el-input placeholder="请输入桥梁名称" clearable v-model="bridgeName" size="small" style="width: 150px" class="mRight10"> </el-input>
          <el-button class="btn" type="primary" size="small" @click="queryForPage(1)">查询</el-button>
        </div>
        <!-- <div class="insp-header-right">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">新建现场处理</el-button>
          <el-button type="success" size="small" icon="el-icon-right" @click="handleDownLoad">导出现场处理单</el-button>
        </div> -->
      </div>
    </div>

    <div class="insp-content">
      <div class="insp-table">
        <el-table
          :data="tableData"
          stripe
          :header-cell-style="{
            background: '#8595B9',
            color: '#fff',
            height: '44px',
          }"
          max-height="660px"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="bridgeName" label="桥梁名称" show-overflow-tooltip></el-table-column>
          <el-table-column prop="maintenanceItemName" label="养护名称" show-overflow-tooltip></el-table-column>
          <el-table-column prop="maintenanceDescribe" label="养护描述" show-overflow-tooltip></el-table-column>
          <el-table-column prop="enterUserName" label="录入人" width="180" show-overflow-tooltip></el-table-column>
          <el-table-column prop="createUserName" label="创建人" width="80" show-overflow-tooltip></el-table-column>
          <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-tooltip content="详情">
                <el-button type="text" icon="el-icon-document" @click="handelDetail(scope.row.id)"> </el-button>
              </el-tooltip>
              <el-tooltip content="修改">
                <el-button type="text" icon="el-icon-edit-outline" @click="handelEdit(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip content="删除">
                <el-button type="text" icon="el-icon-delete" style="color: red !important" @click="handelDelete(scope.row.id)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="insp-page">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          :hide-on-single-page="false"
          @current-change="handlePageChange"
          :page-size="pageSize"
          :total="recordsTotal"
        >
        </el-pagination>
      </div>
    </div>
    <!--新增编辑模板-->
    <vx-popup :title="dialogTitle" width="640px" @close="cancelFormSubmit" :active.sync="dialogVisible" @confirmPopup="handleSubmit" @cancelPopup="cancelFormSubmit">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="桥梁选择 :" prop="bridge">
          <el-select v-model="ruleForm.bridge" placeholder="请选择桥梁" size="small" style="width: 100%" clearable @change="handleChangeBridge">
            <el-option v-for="item in bridgeOptions" :key="item.id" :label="item.name" :value="`${item.id};${item.name}`"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="桥梁类型 :">
          <el-select v-model="ruleForm.bridgeTypeId" placeholder="请选择桥梁类型" size="small" style="width: 100%" :disabled="true">
            <el-option v-for="item in bridgeTypeOptions" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保养项目 :" prop="maintenance">
          <el-select v-model="ruleForm.maintenance" placeholder="请选择保养项目" size="small" style="width: 100%" clearable>
            <el-option v-for="item in maintenanceOptions" :key="item.id" :label="item.minorRepairMaintainName" :value="`${item.id};${item.minorRepairMaintainName}`"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件 :" prop="fileList">
          <el-upload
            :action="uploadUrl"
            list-type="picture-card"
            :file-list="fileList"
            accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG,.PNG,.GIF,.avi,.mpg,.wmv,.3gp,.mov,.mp4,.asf,.flv"
            :before-upload="beforePictureCardUpload"
            :on-remove="handlePictureCardRemove"
            :on-success="handlePictureCardSuccess"
            :data="uploadParams"
            :auto-upload="true"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="保养描述 :" prop="desc">
          <el-input type="textarea" :rows="3" maxlength="200" v-model="ruleForm.desc" show-word-limit> </el-input>
        </el-form-item>
      </el-form>
    </vx-popup>

    <!--小修保养详情-->
    <vx-popup title="小修保养详情" width="780px" @close="cancelDetail" :active.sync="detailVisible" @confirmPopup="cancelDetail" @cancelPopup="cancelDetail">
      <div class="insp-popup-detail">
        <el-row justify="space-between" :gutter="20">
          <el-col :span="12">
            <label>桥梁名称 : </label>
            <span>{{ detailInfo['bridgeName'] || '' }}</span>
          </el-col>
          <el-col :span="12">
            <label>养护名称 : </label>
            <span>{{ detailInfo['maintenanceItemName'] || '' }}</span>
          </el-col>
        </el-row>

        <el-row justify="space-between" :gutter="20">
          <el-col :span="12">
            <label>创建人: </label>
            <span>{{ detailInfo['createUserName'] || '' }}</span>
          </el-col>
          <el-col :span="12">
            <label>录入人 : </label>
            <span>{{ detailInfo['enterUserName'] || '' }}</span>
          </el-col>
        </el-row>

        <el-row justify="space-between" :gutter="20">
          <el-col :span="24">
            <label>上传文件 : </label>
            <span class="imageList">
              <div class="imageList-div" v-for="(item, index) in computedImageList" :key="`${index}image`">
                <el-image v-if="item['isImage']" style="width: 70px; height: 70px" :src="item['filePath']" :preview-src-list="computedImagePrevList"></el-image>
                <div v-else class="imageList-div-video" @click="handleOpenPlayer(item['filePath'])">
                  <em> <img src="@/assets/images/pages/icon_player.png" alt /></em>
                </div>
              </div>
            </span>
          </el-col>
        </el-row>

        <el-row justify="space-between" :gutter="20">
          <el-col :span="24">
            <label>养护描述 : </label>
            <span class="over" :title="detailInfo['maintenanceDescribe'] || ''">{{ detailInfo['maintenanceDescribe'] || '' }}</span>
          </el-col>
        </el-row>
      </div>
    </vx-popup>

    <!--播放器-->
    <vx-popup title="视频播放" width="800px" style="z-index: 51005 !important" @close="handleClosePlayer" :active.sync="playerVisible" :btnGroup="[]">
      <div id="cyberplayerId" style="width: 739px; height: 600px"></div>
    </vx-popup>
  </div>
</template>
<script>
import base from '@/api/base'
export default {
  data() {
    var validateRecordFiles = (rule, value, callback) => {
      if (this.fileList.length <= 0) {
        callback(new Error('请上传文件'))
      } else {
        callback()
      }
    }
    return {
      uploadParams: {},
      uploadUrl: base.UPLOADURL,
      pageSize: 14,
      currentPage: 1,
      recordsTotal: 0,
      bridgeName: '',
      dialogTitle: '新建现场处理',
      dialogVisible: false,
      detailVisible: false,
      playerVisible: false,
      detailInfo: {},
      editId: null,
      tableData: [],
      bridgeOptions: [],
      bridgeTypeOptions: [],
      maintenanceOptions: [],
      ruleForm: {
        bridge: '',
        bridgeTypeId: '',
        maintenance: '',
        desc: '',
      },
      rules: {
        bridge: [
          {
            required: true,
            message: '请选择桥梁',
            trigger: 'change',
          },
        ],
        maintenance: [
          {
            required: true,
            message: '请选择保养项目',
            trigger: 'change',
          },
        ],
        desc: [
          {
            required: true,
            message: '请选择',
            trigger: 'blur',
          },
        ],
        fileList: [
          {
            required: true,
            validator: validateRecordFiles,
            trigger: 'change',
          },
        ],
      },
      fileList: [],
      player: null,
    }
  },
  created() {
    this.queryForPage(1)
    this.queryBridgeOpts()
  },
  methods: {
    queryBridgeOpts() {
      this.$api.bridge.AllTheBridges().then((response) => {
        if (response.data.success) {
          this.bridgeOptions = response.data.data[0]
        }
      })
    },
    queryMaintenanceOpts(val) {
      this.$api.knowledge
        .getList({
          typeId: val,
        })
        .then((response) => {
          if (response.data.success) {
            this.maintenanceOptions = response.data.data[0]
          }
        })
    },
    handleChangeBridge(val) {
      this.uploadParams = {
        ownId: val.split(';')[0],
      }
      this.$api.bridge
        .queryBridgeBasicById({
          bridgeId: val.split(';')[0],
        })
        .then((response) => {
          this.ruleForm.bridgeTypeId = response.data.data[0][0].bridgeTypeId
          const standardId = response.data.data[0][0].standardId
          this.queryBridgeTypes(standardId)
          this.queryMaintenanceOpts(this.ruleForm.bridgeTypeId)
        })
    },
    queryBridgeTypes(val) {
      this.$api.bridge
        .queryBridgeTypeList({
          standardId: val,
        })
        .then((response) => {
          if (response.data.success) {
            this.bridgeTypeOptions = response.data.data[0]
          }
        })
    },
    queryForPage(pageIndex) {
      if (pageIndex && pageIndex === 1) {
        this.currentPage = 1
      }
      const _params = {
        pageSize: this.pageSize,
        pageNum: this.currentPage,
        bridgeName: this.bridgeName,
      }
      this.$api.curing.queryMaintenance(_params).then((response) => {
        if (response.data.success) {
          this.tableData = response.data.data
          this.recordsTotal = response.data.recordsTotal
        }
      })
    },
    handlePageChange(currentPage) {
      this.currentPage = currentPage
      this.queryForPage()
    },
    handleAdd() {
      this.emptyForm()
      this.editId = null
      this.dialogTitle = '新建现场处理'
      this.dialogVisible = true
    },
    handelEdit(val) {
      this.$refs['ruleForm'].resetFields()
      this.dialogTitle = '修改现场处理'
      this.dialogVisible = true
      this.editId = val
      this.queryDetailById(val)
    },
    handelDelete(val) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$api.curing.delMaintenance(val).then((response) => {
            if (response.data.success) {
              this.$vs.notify({
                text: '删除成功',
                color: 'success',
                icon: 'success',
              })
              let maxPage = Math.ceil((this.recordsTotal - 1) / this.pageSize)
              if (this.currentPage > maxPage) {
                this.currentPage = maxPage
              }
              this.handlePageChange(this.currentPage)
            } else {
              this.$vs.notify({
                text: '删除失败',
                color: 'danger',
              })
            }
          })
        })
        .catch(() => {
          this.$vs.notify({
            text: '已取消删除',
            color: 'primary',
          })
        })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleDownLoad() {
      let ids = this.multipleSelection.map((item) => item.id)
      if (ids.length > 0) {
        let _ids = ids.join(',')
        let a = document.createElement('a')
        a.href = `${base.curingUrl}/maintenance_routine/exportExcel?ids=${_ids}`
        document.body.appendChild(a)
        a.click()
        URL.revokeObjectURL(a.href)
        document.body.removeChild(a)
      } else {
        this.$vs.notify({
          text: '请选择保养单！',
          color: 'primary',
        })
      }
    },
    beforePictureCardUpload(file) {
      if (!this.ruleForm.bridge) {
        this.$vs.notify({
          text: '请先选择桥梁！',
          color: 'primary',
        })
        return false
      }
    },
    handlePictureCardRemove(file, fileList) {
      this.handleFileChange(fileList)
    },
    handlePictureCardSuccess(res, file, fileList) {
      this.handleFileChange(fileList)
    },
    handleFileChange(fileList) {
      let _pathList = []
      if (fileList.length > 0) {
        fileList.forEach((item) => {
          if (item.response) {
            if (item.response.code === 200) {
              let _files = item.response.data.successFiles
              if (_files) {
                const _filePath = _files[0].filePath
                _pathList.push({
                  filePath: _filePath,
                  url: `${base.DOWNLOADURL}${_filePath}`,
                })
              }
            }
          } else if (item.status === 'success') {
            _pathList.push({
              filePath: item.filePath,
              url: `${base.DOWNLOADURL}${item.filePath}`,
            })
          }
        })
      }
      this.fileList = _pathList
    },
    emptyForm() {
      this.$refs['ruleForm'].resetFields()
      const emptyObj = {
        bridge: '',
        bridgeType: '',
        maintenance: '',
        desc: '',
      }
      this.fileList = []
      this.ruleForm = emptyObj
    },
    cancelFormSubmit() {
      this.dialogVisible = false
    },
    queryDetailById(val) {
      this.$api.curing.queryMaintenanceDetail(val).then((response) => {
        const _data = response.data.data
        let _ruleForm = {
          bridge: `${_data.bridgeId};${_data.bridgeName}`,
          bridgeTypeId: _data.bridgeType,
          maintenance: `${_data.maintenanceItemId};${_data.maintenanceItemName}`,
          desc: _data.maintenanceDescribe,
        }
        this.fileList = _data.fileVOS
          ? _data.fileVOS.map((item) => ({
              filePath: item.filePath,
              url: `${base.DOWNLOADURL}${item.filePath}`,
            }))
          : []
        this.ruleForm = _ruleForm
        this.handleChangeBridge(_ruleForm.bridge)
      })
    },
    handleSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) {
          return false
        }
        const _fileDTOS = this.fileList.map((item) => ({
          filePath: item.filePath,
        }))

        let _userInfo = JSON.parse(localStorage.getItem('userInfo'))
        let _params = {
          bridgeId: this.ruleForm.bridge.split(';')[0],
          bridgeName: this.ruleForm.bridge.split(';')[1],
          maintenanceItemId: this.ruleForm.maintenance.split(';')[0],
          maintenanceItemName: this.ruleForm.maintenance.split(';')[1],
          maintenanceDescribe: this.ruleForm.desc || '',
          enterUserId: _userInfo['userid'] || '',
          enterUserName: _userInfo['realname'] || '',
          createUserId: _userInfo['userid'] || '',
          createUserName: _userInfo['realname'] || '',
          bridgeType: this.ruleForm.bridgeTypeId,
          fileDTOS: _fileDTOS,
        }
        if (this.editId) {
          _params.id = this.editId
        }
        if (this.editId) {
          this.$api.curing.updateMaintenance(_params).then((response) => {
            if (response.data.success) {
              this.$vs.notify({
                text: '修改成功',
                color: 'success',
              })
              this.dialogVisible = false
              this.queryForPage(1)
              this.fileList = []
            }
          })
        } else {
          this.$api.curing.addMaintenance(_params).then((response) => {
            if (response.data.success) {
              this.$vs.notify({
                text: '新增成功',
                color: 'success',
              })
              this.dialogVisible = false
              this.queryForPage(1)
              this.fileList = []
            }
          })
        }
      })
    },
    queryInfoById(val) {
      this.$api.curing.queryMaintenanceDetail(val).then((response) => {
        this.detailInfo = response.data.data || {}
      })
    },
    handelDetail(val) {
      this.detailVisible = true
      this.queryInfoById(val)
    },
    cancelDetail() {
      this.detailVisible = false
    },
    handleOpenPlayer(url) {
      this.playerVisible = true
      this.player = cyberplayer('cyberplayerId').setup({
        width: '739px',
        height: '600px',
        backcolor: 'transparent',
        stretching: 'uniform',
        file: url,
        image: '',
        autostart: false,
        stretching: 'uniform',
        repeat: true,
        volume: 100,
        controls: true,
        starttime: 0,
        ak: 'DHnZkSt2n5Gv8CKlt4RxsjS8M67UvKOU', //陈诚账号
      })
    },
    handleClosePlayer() {
      this.playerVisible = false
      if (this.player) {
        this.player.remove()
        this.player = null
      }
    },
  },
  computed: {
    computedImageList() {
      let _list = this.detailInfo['fileVOS'] ? this.detailInfo['fileVOS'] : []
      let _extsString = '.jpg.jpeg.png.gif.JPG.JPEG.PNG.GIF'
      return _list.map((item) => {
        let _ext = item['filePath'].substring(item['filePath'].lastIndexOf('.') + 1)
        return {
          isImage: _extsString.indexOf(_ext) != -1 ? true : false,
          filePath: `${base.DOWNLOADURL}${item.filePath}`,
        }
      })
    },
    computedImagePrevList() {
      let _list = this.detailInfo['fileVOS'] ? this.detailInfo['fileVOS'] : []
      let _extsString = '.jpg.jpeg.png.gif.JPG.JPEG.PNG.GIF'
      return _list.map((item) => {
        let _ext = item['filePath'].substring(item['filePath'].lastIndexOf('.') + 1)
        if (_extsString.indexOf(_ext) != -1) {
          return `${base.DOWNLOADURL}${item.filePath}`
        }
      })
    },
  },
}
</script>
<style scoped lang="scss">
@import '@/views/inspection/insp.scss';

/deep/.el-table__header tr,
/deep/.el-table__header th {
  padding: 0;
  height: 44px;
}

/deep/.el-table td,
/deep/.el-table th {
  text-align: center;
  font-size: 14px;
}

/deep/.el-table th {
  font-weight: 500;
  color: #fff;
}

/deep/.el-table td {
  font-weight: 400;
  color: #444;
  padding: 0;
  height: 44px;
  line-height: 44px;
}

/deep/.el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #f1f5fc;
}

/deep/.el-upload--picture-card {
  width: 70px;
  height: 70px;
  line-height: 74px;
}

/deep/.el-upload-list--picture-card .el-upload-list__item {
  width: 72px;
  height: 72px;
}

.btn {
  margin-left: 20px;
}
</style>
